package com.xidian.zhiancloud.service.workTicket;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.dao.workTicket.FireMapper;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.dto.workTicket.FireTicketVODTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.workTicket.FireTicket;
import com.xidian.zhiancloud.qo.workTicket.FireTicketQO;
import com.xidian.zhiancloud.vo.workTicket.FireTicketVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class FireService extends ServiceImpl<FireMapper, FireTicket> implements IService<FireTicket> {
    @Autowired
    private FireMapper fireMapper;

    @Autowired
    private FireFlowService fireFlowService;

    @Autowired
    private OrganizationMapper organizationMapper;

    /**
     * 列表查找
     * @param fireTicketQO
     * @return
     */
    public IPage<FireTicketVO> getListByQO(FireTicketQO fireTicketQO) {
        Page<FireTicketVO> fireTicketPage = new Page<>(fireTicketQO.getCurrent(), fireTicketQO.getSize());
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn("create_time").setAsc(false);
        fireTicketPage.getOrders().add(orderItem);
        IPage<FireTicketVO> res = fireMapper.getListByQO(fireTicketPage, fireTicketQO);
        return res;
    }


    /**
     * 设置小步骤的isCommit**字段为1，表示已提交
     *
     * @param subStep
     * @param fireTicket
     */
    public FireTicket setSubStepFinish(Integer subStep, FireTicket fireTicket) {
        switch (subStep) {
            case 1: fireTicket.setIsCommit1(1); break;
            case 2: fireTicket.setIsCommit2(1); break;
            case 3: fireTicket.setIsCommit3(1); fireTicket.setWorkerSignTime(new Date(System.currentTimeMillis())); break;
            case 4: fireTicket.setIsCommit4(1); fireTicket.setDanger1Time(new Date(System.currentTimeMillis())); break;
            case 5: fireTicket.setIsCommit5(1); fireTicket.setDanger2Time(new Date(System.currentTimeMillis())); break;
            case 6: fireTicket.setIsCommit6(1); break;
            case 7: fireTicket.setIsCommit7(1); break;
            case 8: fireTicket.setIsCommit8(1); break;
            case 9: fireTicket.setIsCommit9(1); break;
            case 10: fireTicket.setIsCommit10(1); break;
            case 11: fireTicket.setIsCommit11(1); fireTicket.setProductUnitTime(new Date(System.currentTimeMillis())); break;
            case 12: fireTicket.setIsCommit12(1); fireTicket.setSafeUnitTime(new Date(System.currentTimeMillis())); break;
            case 13: fireTicket.setIsCommit13(1); fireTicket.setApproveTime(new Date(System.currentTimeMillis())); break;
            case 14: fireTicket.setIsCommit14(1); fireTicket.setReviewBeforeWorkTime(new Date(System.currentTimeMillis())); break;
            case 15: fireTicket.setIsCommit15(1); fireTicket.setFinishCheck1Time(new Date(System.currentTimeMillis())); break;
            case 16: fireTicket.setIsCommit16(1); break;

        }
        return fireTicket;
    }


    /**
     * 根据fireTicket的id生成VO对象
     *
     * @param id
     * @return
     */
    public FireTicketVODTO getFireTicketVODTOById(Long companyId, Long id) {
        FireTicketVODTO fireTicketVODTO = new FireTicketVODTO();
        // DTO = VO + Map
        FireTicketVO fireTicketVO = new FireTicketVO();
        FireTicket fireTicket = fireMapper.selectById(id);
        if (fireTicket == null) {
            throw new CustomizeException(GeneralResponseEnums.GET_FAILED);
        }
        // 将根据id得到的fireTicket字段值，复制到fireTicketVO字段中
        BeanUtils.copyProperties(fireTicket, fireTicketVO);
        // 查找-设置部门名称
        Organization organization = organizationMapper.selectById(fireTicket.getApplicantUnitId());
        fireTicketVO.setApplicantUnitName(organization == null ? "该部门不存在" : organization.getName());
        // 处理动火方式字段
        String risk_s = fireTicketVO.getWorkType();
        if (risk_s != null) {
            List<String> risks = new LinkedList<>();
            for(String risk : risk_s.split(",")) {
                risks.add(risk);
            }
            fireTicketVO.setWorkTypeList(risks);
        }
        // 处理危险作业1和2的列表
        String danger1_s = fireTicketVO.getDanger1();
        if (danger1_s != null) {
            List<String> danger1s = new LinkedList<>();
            for (String danger1 : danger1_s.split(",")) {
                danger1s.add(danger1);
            }
            fireTicketVO.setDanger1List(danger1s);
        }
        String danger2_s = fireTicketVO.getDanger1();
        if (danger2_s != null) {
            List<String> danger2s = new LinkedList<>();
            for (String danger2 : danger2_s.split(",")) {
                danger2s.add(danger2);
            }
            fireTicketVO.setDanger1List(danger2s);
        }
        // 处理关联作业票
        String relateWorkNum_s = fireTicketVO.getRelateWorkNum();
        if (relateWorkNum_s != null) {
            List<String> relateWorkNums = new LinkedList<>();
            for (String relateWorkNum : relateWorkNum_s.split(",")) {
                relateWorkNums.add(relateWorkNum);
            }
            fireTicketVO.setRelateWorkNumList(relateWorkNums);
        }

        // 获取enableFieldMap
        Integer currentStep = fireTicket.getCurrentStep();
        // 根据大步骤在fire_flow中获取子步骤列表
        List<Long> subStepList = fireFlowService.getSubIdsByCurrent(companyId, currentStep);
        // 根据当前步骤调用函数，返回List<map<人员id,List<可编辑字段>>>
        List<Map<List<Long>, List<String>>> enableField = fireFlowService.getEnableFieldMap(companyId, currentStep, subStepList);

        // 判断该作业票的提交签字已经超时作废
        if (fireTicket.getFireAnalyse1Time() != null) {
            Integer workLevel = fireTicket.getWorkLevel();
            Date nowTime = new Date(System.currentTimeMillis());
            Date analyseTime = fireTicket.getFireAnalyse1Time();
            Boolean isOverDate = fireFlowService.signOvertime(analyseTime, nowTime, workLevel);
            if (isOverDate == true) {
                fireTicketVO.setIsOverTime(1);
            }
        }

        fireTicketVODTO.setFireTicketVO(fireTicketVO);
        fireTicketVODTO.setEnableFieldMap(enableField);
        return fireTicketVODTO;
    }



    /**
     * 根据relateWorkNum，查找对应的t_fire的id
     *
     * @param relateWorkNum
     * @return
     */
    public Long getRelateTicket(String relateWorkNum, Long companyId) {
        Long relateId = null;
        LambdaQueryWrapper<FireTicket> query = Wrappers.<FireTicket>lambdaQuery();
        query.eq(FireTicket::getCompanyId, companyId);
        List<FireTicket> fireTicket = fireMapper.selectList(query);

        for (int i = 0; i < fireTicket.size(); i++) {
            // 根据字符串内容判断是否相等
            if (fireTicket.get(i).getWorkNumber().equals(relateWorkNum)) {
                relateId = fireTicket.get(i).getId();
                break;
            }
        }
        return relateId;
    }


}

